package org.paradise.dms.dao.impl;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.builder.ReflectionToStringBuilder;
import org.apache.log4j.Logger;
import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.paradise.dms.pojo.Apartment;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.stereotype.Service;

import com.dheaven.framework.dao.BaseHibernateDao;
import com.dheaven.framework.dao.DaoException;

@Service
public class ApartmentDAOImpl extends BaseHibernateDao<Apartment> {
	private static Logger log = Logger.getLogger(ApartmentDAOImpl.class);

	/**
	 * 
	 * Description: 查询所有公寓
	 * 
	 * @Version1.0 2009-3-18 下午12:50:42 李双江（paradise.lsj@gmail.com）创建
	 * @version1.1 2009-3-31 上午01:53:59 闫克 （kurtyan777@gmail.com） 修改
	 *             增加了insertApartment方法
	 * 
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<Apartment> listAllApartment() {
		List<Apartment> list = null;
		list = this.find("from Apartment where apartmentind=1");
		return list;
	}

	/**
	 * 
	 * Description: 返回数据库公寓的总条数
	 * 
	 * @Version1.0 2009-3-30 上午01:34:32 李双江（paradise.lsj@gmail.com）创建
	 * @return
	 */
	public int getAllApartmentRows() {
		return this.find("from Apartment where apartmentind=1").size();
	}

	/**
	 * 
	 * Description: 通过id查找公寓
	 * 
	 * @Version1.0 2009-3-20 上午03:07:18 李双江（paradise.lsj@gmail.com）创建
	 * @Version1.1 2009-4-19 17：32 李双江 修改给通过id查询公寓
	 * @param apartmentname
	 * @return
	 * @throws DaoException
	 */
	/*
	@SuppressWarnings("unchecked")
	public List<Apartment> findApartmentByID(String apartmentid) throws DaoException {
		Apartment apt = (Apartment) this.find("from Apartment a where a.apartmentid = ? and a.apartmentind=1", new Object[] { apartmentid }).get(0);
		String[] aptid = { apt.getApartmentid() };
		// 设置公寓的可入住和已经入住人数情况 4/13/2009 By Paradise
		List lst = this.findTotalRoomsAndAvailRoomsByApartmentID(aptid);
		for (int k = 0; k < lst.size(); k++) {
			List li = (List) lst.get(k); // 每个存储过程查询出来的lst值只有一个
			for (int t = 0; t < li.size(); t++) {
				Object[] o = (Object[]) li.get(t);
				// log.info("object[]长度：" + o.length);
				if (o.length == 1) {
					apt.setApartmenttotalrooms(o[0] + "");
					apt.setApartmentavailrooms("0");
				} else {
					apt.setApartmenttotalrooms(o[0] + "");
					apt.setApartmentavailrooms(o[1] + "");
				}
			}
		}
		List<Apartment> aptList = new ArrayList<Apartment>();
		aptList.add(apt);
		log.info("DMS_info:aptList是：" + ReflectionToStringBuilder.toString(aptList.get(0)).toString());
		return aptList;
	}
	*/
	/**
	 * 
	 * Description:调用存储过程察看指定公寓id入住人数和可住人数
	 * 
	 * @Version1.0 2009-3-20 上午11:29:30 李双江（paradise.lsj@gmail.com）创建
	 * @param apartmentid
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List findTotalRoomsAndAvailRoomsByApartmentID(final String[] apartmentid) {
		return getHibernateTemplate().executeFind(new HibernateCallback() {
			public Object doInHibernate(org.hibernate.Session s) throws HibernateException, SQLException {
				List st = new ArrayList();
				SQLQuery query = (SQLQuery) s.createSQLQuery("{call GetTotalAvailByApartId(?)}").addScalar("total", Hibernate.INTEGER).addScalar("avail", Hibernate.INTEGER);
				for (int m = 0; m < apartmentid.length; m++) {
					query.setInteger(0, Integer.parseInt(apartmentid[m]));
					st.add(query.list());
				}
				return st;
			}
		});
	}

	/**
	 * 
	 * Description: 把所有的apartment表信息都查出来。方便页面select用嘛！
	 * 
	 * @Version1.0 2009-3-24 下午09:49:31 李双江（paradise.lsj@gmail.com）创建
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List findAllApartInfo() {
		return getHibernateTemplate().executeFind(new HibernateCallback() {
			public Object doInHibernate(org.hibernate.Session s) throws HibernateException, SQLException {
				return s.createQuery("from Apartment where apartmentind=1").list();
			}
		});
	}

	/**
	 * 
	 * Description: 楼宇管理里面分页显示所有的公寓列表
	 * 
	 * @Version1.0 2009-3-30 上午01:37:23 李双江（paradise.lsj@gmail.com）创建
	 * @param pageSize
	 * @param startRow
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<Apartment> listAllApartmentByPage(int pageSize, int startRow) {
		final int pageSize1 = pageSize;
		final int startRow1 = startRow;
		Query query = this.createQuery("from Apartment where apartmentind=1");
		query.setFirstResult(startRow1);
		query.setMaxResults(pageSize1);
		return (List<Apartment>) query.list();
	}

	/**
	 * 
	 * Description:根据apartmentid，删除一条公寓
	 * 
	 * @Version1.0 2009-3-30 下午08:54:37 李双江（paradise.lsj@gmail.com）创建
	 * @param apartmentid
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public String deleteApartmentbyApartmentID(final String apartmentid) {
		String statusMsg = "";

		List lst = this.getHibernateTemplate().executeFind(new HibernateCallback() {
			public List doInHibernate(org.hibernate.Session session) {
				SQLQuery query = (SQLQuery) session.createSQLQuery("call gettotalavailbyapartid(?)");
				query.setInteger(0, Integer.parseInt(apartmentid));
				return query.list();
			}
		});
		Object[] obj = (Object[]) lst.get(0);
		if (Integer.parseInt(obj[1] + "") > 0) {
			log.warn("DMS_warn:公寓楼不为空，无法删除！");
			statusMsg = "DMS_warn:公寓楼不为空，无法删除！";
			return statusMsg;
		}

		Apartment aprtmt = null;
		try {
			aprtmt = (Apartment) this.find("from Apartment where apartmentid=?", new Object[] { apartmentid }).get(0);
			aprtmt.setApartmentind("0");
			this.update(aprtmt);
			statusMsg = "删除公寓成功！";
			log.info("DMS_info：" + "删除id为" + apartmentid + "的公寓成功");
		} catch (DaoException e) {
			e.printStackTrace();
			statusMsg = "公寓信息查询有误！";
			log.error("DMS_error：公寓信息查询有误！");
			log.error("DMS_error：失败原因 " + e);
		}
		return statusMsg;
	}

	/**
	 * Description: 创建一条apartment
	 * 
	 * @version 1.0 2009-3-31 上午 02:30:59 闫克 （kurtyan777@gmail.com） 创建
	 * @param apartment
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public String insertApartment(Apartment apartment) {
		String statusMsg = "";
		try {
			List<Apartment> aptList = this.find("from Apartment where apartmentname=? and apartmentind=1", new Object[] { apartment.getApartmentname() });
			if (aptList.size() > 0) {
				statusMsg = "该公寓已存在!";
				log.warn("DMS_warn：" + ReflectionToStringBuilder.toString(apartment).toString() + "公寓名重复，公寓已经存在！");
				return statusMsg;
			}
		} catch (DaoException e1) {
			log.error("DMS_error：" + ReflectionToStringBuilder.toString(apartment).toString() + "创建公寓失败 ！");
			log.error("DMS_error：失败原因 " + e1);
			statusMsg = "Error!";
			return statusMsg;
		}

		try {
			this.create(apartment);
			log.info("DMS_info：" + ReflectionToStringBuilder.toString(apartment).toString() + "创建公寓成功！");
			statusMsg = "创建公寓成功！";
			return statusMsg;
		} catch (DaoException e) {
			log.error("DMS_error：" + ReflectionToStringBuilder.toString(apartment).toString() + "创建公寓失败 ！");
			log.error("DMS_error：失败原因 " + e);
			statusMsg = "创建公寓失败！";
			return statusMsg;
		}
	}
}
